package it.unipd.dei.bd.icineasti.database;

import it.unipd.dei.bd.icineasti.resource.Sala;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.sql.ResultSet;

/**
 * Crea una sala nel database e ritorna l'id che le è stato assegnato
 * dal db stesso.
 * 
 * @author Bardelle Renzo
 * @version 1.00
 */

public class CreateSalaDatabase {

	private static final String STATEMENT = "INSERT INTO sala (sigla, nome, totaleposti, codicesede, idsala) VALUES ( ?, ?, ?, ?, DEFAULT) RETURNING idsala";

	private final Connection con;
	private final Sala sala;

	public CreateSalaDatabase(Connection con, Sala sala) {
		this.con = con;
		this.sala = sala;
	}

	public int createSala() throws SQLException {

		PreparedStatement pstmt = null;
		ResultSet rs = null;
		int idsala = -1;
		
		try {
			pstmt = con.prepareStatement(STATEMENT);
			
			pstmt.setString(1, sala.getSigla());
			pstmt.setString(2, sala.getNome());
			pstmt.setInt(3, sala.getTotalePosti());
			pstmt.setInt(4, sala.getCodiceSede());
			
			rs = pstmt.executeQuery();
			
			rs.next();

			idsala = rs.getInt("idsala");
			
		} finally {
			if (rs != null) {
				rs.close();
			}

			if (pstmt != null) {
				pstmt.close();
			}
			
			con.close();
		}
		
		return idsala;
	}
}
